//
//  Request.m
//  HollyPhoneSdk
//
//  Created by hollycrm on 2023/3/7.
//  网络请求

#import "Request.h"

@implementation Request
-(void)post:(NSMutableDictionary *)params withUrl:(NSString *)url succ:(void (^)(NSDictionary * _Nonnull))succed fail:(void (^)(NSString * _Nonnull))failed{
    
        NSURLSession * mySession = [NSURLSession sharedSession ];
        NSURL * fullURL = [ NSURL URLWithString :url];
        NSMutableURLRequest * request = [ NSMutableURLRequest requestWithURL :fullURL cachePolicy : NSURLRequestUseProtocolCachePolicy timeoutInterval : 15.0 ];
        request. HTTPMethod = @"POST" ;
        [request addValue : @"application/json" forHTTPHeaderField : @"Content-Type" ];
    [request addValue : @"application/json" forHTTPHeaderField : @"Accept" ];
    
    
    NSData *data=[NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil];
    request. HTTPBody = data;
    
        NSURLSessionDataTask * task = [mySession dataTaskWithRequest :request completionHandler :^( NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            // 判断接口是否成功返回
            if (error) {
                // 接口访问失败
                //NSLog ( @"error:%@" ,error. localizedDescription );
                //NSLog ( @"%s" ,__func__);
              
                if (failed) {
                    failed(@"请求失败，请稍后再试");
                }
            } else
            {
                // 接口访问成功
                //JSON 解析
                NSError * parseError1 = nil ;
                NSDictionary * dic = [ NSJSONSerialization JSONObjectWithData :data options : NSJSONReadingMutableContainers error :&parseError1];
                if (parseError1) {
                   // NSLog ( @"parse failed" );
                    return ;
                }
                //NSLog ( @"data:%@" , dic);
               
                bool success = [[dic objectForKey:@"success"] boolValue];
                
                bool succ = [[dic objectForKey:@"Succeed"] boolValue];
                if (succ || success) {
                    if (succed) {
                        dispatch_async ( dispatch_get_main_queue (), ^{
                            succed(dic);
                        });
                    }
                } else {
     
                    if (failed) {
                        dispatch_async ( dispatch_get_main_queue (), ^{
                            NSString *msg = [dic valueForKey:@"Message"];
                            if (msg != nil) {
                            failed(msg);
                            }
                            else if ([dic valueForKey:@"message"] != nil){
                                failed([dic valueForKey:@"message"]);
                            }
                            else{
                                failed(@"请求服务器异常");
                            }
                        });
                    }
                }
            }
           
        }];
        [task resume];
    
}

-(void)get:(NSMutableDictionary *)params withUrl:(NSString *)url succ:(void (^)(NSDictionary * _Nonnull))succed fail:(void (^)(NSString * _Nonnull))failed{
   
 NSURLSessionConfiguration * config = [NSURLSessionConfiguration defaultSessionConfiguration];
 config.timeoutIntervalForRequest = 15.0;
 NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
    NSMutableString *fullurl = [NSMutableString stringWithString:url];
    [fullurl appendString:@"?"];
    for (NSString *key in params.allKeys){
        [fullurl appendString:[NSString stringWithFormat:@"%@=%@&",key,[params objectForKey:key]]];
    }
    NSURL *requestUrl = [NSURL URLWithString:fullurl ];
    
    
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:requestUrl completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        dispatch_async ( dispatch_get_main_queue (), ^{
            if (error != nil) {
                // Handle error
                if (failed) {
                    failed(@"请求失败，请稍后再试");
                }
            } else {
                // Process the response data
                NSError * parseError1 = nil ;
                NSDictionary * dic = [ NSJSONSerialization JSONObjectWithData :data options : NSJSONReadingMutableContainers error :&parseError1];
                if (parseError1) {
                   // NSLog ( @"parse failed" );
                    failed(@"返回数据异常，请稍后再试");
                    return ;
                }
               // NSLog ( @"data:%@" , dic);
                succed(dic);
            }
        });
    }];
    [dataTask resume];
}

@end
